package com.hwatsang.remote.rest;

import java.io.IOException;
import java.io.InterruptedIOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpAccessHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpAccessHelper.class);
	
	private static DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());
	
	private static final int MAX_RETRY = 3;
	
	static {		
		client.setHttpRequestRetryHandler(
			new HttpRequestRetryHandler() {
			    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
			        if (executionCount >= MAX_RETRY) {
			            // Do not retry if over max retry count
			            return false;
			        }
			        if (exception instanceof InterruptedIOException) {
			            // Timeout
			            return true;
			        }		
			        return false;
			    }
	
			});
	}
	
	/**
	 * 
	 * @param url
	 * @throws IOException
	 */
	public static String executeGetWithoutParam(final String url) throws IOException{
		HttpGet get = new HttpGet(url);
						
		logger.debug("Going to access url {}.", url);
		
		return client.execute(get, new ResponseHandler<String>() {
		    public String handleResponse(
		            HttpResponse response) throws IOException {
		    	
		    	logger.debug("Remote server response {} for url {}.", response.getStatusLine().getStatusCode(), url);
		    	
		    	if(response.getStatusLine().getStatusCode() != 200){
					throw new IOException("Http request failed with status code " + response.getStatusLine().getStatusCode());
				}
		    	
		        HttpEntity entity = response.getEntity();
		        if (entity != null) {
		            return EntityUtils.toString(entity);
		        } else {
		            return null;
		        }
		    }
		});				
	}
		
}
